package dao;

import entity.Atm;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class AtmDao {

    String driver = "com.mysql.cj.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/atm?serverTimezone=CST";
    String user = "root";
    String password = "123456";
    public Atm selectOne(String name){
        Atm atm = null;
        String sql = "SELECT `NAME`,PASSWORD,BALANCE FROM ATM WHERE `NAME` = ?";
        try {
            Class.forName(driver);
            Connection conn = DriverManager.getConnection(url,user,password);
            PreparedStatement pstat = conn.prepareStatement(sql);
            pstat.setString(1,name);
            ResultSet rs = pstat.executeQuery();
            if(rs.next()){
                //将结果集中的信息取出来 存入另一个小容器内(domain对象)
                atm = new Atm();
                atm.setName(rs.getString("name"));
                atm.setPassword(rs.getString("password"));
                atm.setBalance(rs.getFloat("balance"));
            }
            rs.close();
            pstat.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return atm;
    }

    //dao的更新方法
    public void update(Atm atm){

        String sql = "UPDATE ATM SET PASSWORD = ? , BALANCE = ? WHERE `NAME` = ?";
        try {
            Class.forName(driver);
            Connection conn = DriverManager.getConnection(url,user,password);
            PreparedStatement pstat = conn.prepareStatement(sql);
            pstat.setString(1,atm.getPassword());
            pstat.setFloat(2,atm.getBalance());
            pstat.setString(3,atm.getName());
            pstat.executeUpdate();
            pstat.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
